using System;
using System.IO;

using IBatisNet.DataMapper;
using IBatisNet.DataMapper.Configuration;

using log4net;

using GymManager.Exception;

namespace GymManager.Persistence
{
    /// <summary>
    /// Class responsible by connecting with database
    /// </summary>
    public class DAOManager
    {
        // Ibatis singleton object instance
        private static ISqlMapper _ibatisMapper = null;

        // logger instance
        private static ILog _logManager = LogManager.GetLogger(typeof(DAOManager));

        /// <summary>
        ///     Method responsible by getting a instace of interface responsible by
        ///     database connection.
        /// </summary>
        /// <returns> ISqlMapper - Singleton Instance </returns>
        /// <exception cref="GymManager.Persistence.PersistenceException"/>
        public static ISqlMapper getInstance()
        {
            if (_ibatisMapper == null )
            {
                try
                {
                    // getting sqlMap config reference
                    Stream sqlMapConfigStream = typeof(DAOManager).Assembly.GetManifestResourceStream("GymManager.configuration.ibatis.sqlMap.config");
                    
                    // configurating ibatis mapper
                    DomSqlMapBuilder builder = new DomSqlMapBuilder();
                    _ibatisMapper = builder.Configure(sqlMapConfigStream);
                }
                catch (System.Exception ex)
                {
                    _logManager.Error("Error trying to obtain a Ibatis Mapper Instance", ex);
                    throw new PersistenceException("Error trying to obtain a Ibatis Mapper Instance", ex);
                }
            }            

            return _ibatisMapper;
        }
    }
}
